package com.cc8w.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.dom4j.DocumentException;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.cc8w.entity.CompanyAndTypeListPojo;
import com.cc8w.entity.CompanyAndTypePojo;
import com.cc8w.entity.CompanyPojo;
import com.cc8w.entity.TeacherPojo;
import com.cc8w.entity.UserPojo;
import com.cc8w.service.UserService;
import com.cc8w.util.RequestData;
import com.cc8w.util.ReturnData;

@Controller
@RequestMapping("/home/helloworld")
public class HelloWorld extends BaseController {
	
	@Value("${url}")  
	private String url;   //注入xml的db.properties
	@Autowired
	private UserService userService;
	

    @RequestMapping("/hi.do")
    public String hi()
    {
        System.out.println("hi.dodo");
        return "hi";
    }
    @RequestMapping("/test")
    public ModelAndView  test(HttpServletRequest request, HttpServletResponse response,Model model) throws IOException, DocumentException, FileUploadException {
    	
    	System.out.println(url); //属性

    	
    	UserPojo up = userService.queryUserOne();
    	System.out.println(up);
    	model.addAttribute("UserPojo", up);
    	
       
//    	TeacherPojo tp = userService.queryTeacherOne();
//    	System.out.println(tp);
//
//    	ReturnData rp = userService.queryTeacherOneByMap();
//    	System.out.println(rp);

//    	//1.加载配置文件
//        String resource = "mybatis-config.xml";
//        InputStream inputStream = Resources.getResourceAsStream(resource);
//        SqlSessionFactory sqlSessionFactory =
//        new SqlSessionFactoryBuilder().build(inputStream);
//    	
//    	//2.获取SqlSession-->类似于数据库连接 Connection
//        SqlSession session = sqlSessionFactory.openSession();
//        //3.执行XXMapper.xml中映射的sql语句
//        String stm = "com.cc8w.mapper.UsersMapper.queryUserOne";
//        UserPojo t = session.selectOne(stm);
//        System.out.println(t);
    	
    	
    	RequestData rd = new RequestData(request);
    	
//    	String cars = rd.getString("cars");
//    	String[] vehicle = rd.getStrArr("vehicle");
//    	int sex = rd.getInt("sex");
//    	
//    	System.out.println(cars);
//    	System.out.println(vehicle[0]);
//    	System.out.println(sex);
    	
    	//项目名称
    	String path = request.getContextPath();
    	//项目网址加项目名称
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    
        
        ModelAndView mav = new ModelAndView("home/helloworld/test");
        mav.addObject("APP_PATH", path);
        mav.addObject("BASE_PATH", basePath);
        return mav;
    }
    @RequestMapping("/test1")
    public String  test1 () 
    {

        //model.addAttribute("user", "1111");
    	
        return "home/helloworld/test1";	
 	
    }

	@RequestMapping("/simpleparam")
    public String  simpleparam (@RequestParam("company_name") String c_name,@RequestParam("company_phone") String c_tel) 

    {

        //model.addAttribute("user", "1111");
    	this.model.addAttribute("action_type", "简单类型搜索结果:");
    	
		HashMap<String,String> hm = new HashMap<String,String>();
    	hm.put("company_name", c_name);
    	hm.put("company_phone", c_tel);
		String req_data = JSON.toJSONString(hm);
		this.model.addAttribute("req_data", req_data);
        return "home/helloworld/test1";	
 	
    }
    @RequestMapping("/classparam")
    public String  classparam (@Valid CompanyPojo companyPojo,BindingResult result) 
    {
    	System.out.println(result.getErrorCount());
    	if(result.getErrorCount()>0) {
    		for(FieldError error : result.getFieldErrors()) {
    			System.out.println(JSON.toJSONString(error));
    			
    		}
    	}
    	
    	
        //model.addAttribute("user", "1111");
    	this.model.addAttribute("action_type", "包装类型搜索结果:");
    	String req_data = JSON.toJSONString(companyPojo);
		this.model.addAttribute("req_data", req_data);
        return "home/helloworld/test1";	
 	
    }
    @RequestMapping("/classparam2")
    public String  classparam2 (@Valid CompanyAndTypePojo companyAndType,BindingResult result) 
    {
    	System.out.println(result.getErrorCount());
    	if(result.getErrorCount()>0) {
    		for(FieldError error : result.getFieldErrors()) {
    			System.out.println(JSON.toJSONString(error));
    			
    		}
    	}
    	
    	//实例化要测试的Bean
    	CompanyPojo cp = new CompanyPojo();
    	cp.setC_name("1");
    	cp.setId(1);
    	
    	//1.创建工厂
    	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    	//2.通过工厂获取校验对象validator
    	Validator validator = factory.getValidator();
    	//3.校验模型对象
    	Set<ConstraintViolation<CompanyPojo>> constraintViolation = validator.validate(cp);
    	//4.通过iterator遍历校验后的结果
    	Iterator<ConstraintViolation<CompanyPojo>>iterator = constraintViolation.iterator();
    	
    	while(iterator.hasNext()) {
    		ConstraintViolation<CompanyPojo> cat = iterator.next();
    		System.out.println(cat.getPropertyPath());//出错的字段名
    		System.out.println(cat.getMessage());//出错的信息
    	}
    	
    	
        //model.addAttribute("user", "1111");
    	this.model.addAttribute("action_type", "包装类型搜索结果:");
    	String req_data = JSON.toJSONString(companyAndType);
		this.model.addAttribute("req_data", req_data);
        return "home/helloworld/test1";	
 	
    }
    @RequestMapping("/listparam")
    public String  listparam (@Valid CompanyAndTypeListPojo ctlps,BindingResult result) 
    {
    	//ArrayList<CompanyAndTypePojo> ctlp = ctlps.getCompanyAndType();
 
    	System.out.println(result.getErrorCount());
    	if(result.getErrorCount()>0) {
    		for(FieldError error : result.getFieldErrors()) {
    			System.out.println(JSON.toJSONString(error));
    			
    		}
    	}
    	//或
    	
		if(result.hasErrors()){
		    for (ObjectError error : result.getAllErrors()) {
		        System.out.println(error.getDefaultMessage());
		    }
		}


  	
        //model.addAttribute("user", "1111");
    	this.model.addAttribute("action_type", "集合类型(map,list)搜索结果");
       	String req_data = JSON.toJSONString(ctlps);
    		this.model.addAttribute("req_data", req_data);
        return "home/helloworld/test1";	
 	
    }
    

    @RequestMapping("/mapparam")
    public String  mapparam () 
    {
    	
        //model.addAttribute("user", "1111");
    	this.model.addAttribute("action_type", "集合类型(map,list)搜索结果");
        return "home/helloworld/test1";	
 	
    }
    
    
    
}